package com.bitcat.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {


    MediaPlayer mediaPlayer;

    Timer timer;


    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }


    class MyBinder extends Binder{



        //音乐开始播放
        public void start(){
            if (mediaPlayer != null){
                mediaPlayer.reset();
            }
            mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.snow);
            mediaPlayer.start();
            addTimer();
        }

        //暂停音乐
        public void pause(){
            mediaPlayer.pause();
        }

        //继续播放
        public void continuePlay(){
            mediaPlayer.start();
        }

        //停止播放
        public void exit(){
            mediaPlayer.stop();
            mediaPlayer.release();
        }


        public void seekTo(int progress) {
            mediaPlayer.seekTo(progress);
        }
    }


    public void addTimer(){
        if (timer == null){
            timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    if (mediaPlayer == null){
                        return;
                    }
                    //获取音乐的总时长和当前播放进度
                    int duration = mediaPlayer.getDuration();
                    int currentPosition = mediaPlayer.getCurrentPosition();

                    Intent intent = new Intent("update");
                    intent.putExtra("duration",duration);
                    intent.putExtra("currentPosition",currentPosition);
                    sendBroadcast(intent);
                }
            };
            timer.schedule(timerTask,100,1000);
        }
    }
}